const userModel=require('../../models/element-admin/user')
const { creataToken} = require('../../utils/jwt')
const jwt = require('jsonwebtoken')
class UserController{

    static async login(ctx){
        let {username,password}=ctx.request.body
        let userna=await userModel.findOne({username})
        if(userna){
        if(userna.password===password) {
            // 生成token并返回token
            const token = creataToken(userna)
            ctx.body = { err: 0, msg: '登录成功', data: { token }} 
        }else{
            ctx.body = { err: 1, msg: '用户名和密码不匹配', data: {}}
        }
        }else{
            ctx.body = { err: 1, msg: '该用户不存在', data: {}}
        }

    }
    //根据token获取用户信息
    static async getUserInfo(ctx){
        const {token}=ctx.request.query
        var decoded =jwt.verify(token, 'yyx')
        const u = decoded.data
        const info = await userModel.findOne({username: u.username})
        const roles = info.role.split(';').filter(e=>e)
        ctx.body = {
          err: 0,
          msg: 'success',
          data: {
            roles,
            nike_name:info.role_name,
            status:info.status
          }
        }
      }

      // 获取用户列表
    static async getList(ctx){
      let { name,page,size } = ctx.request.query
      page= parseInt(page || 1)
      size= parseInt(size || 10)
      const params = {
        username: new RegExp((name||''), 'img')
      }
      const total = await userModel.find(params)
      const list = await userModel.find(params).limit(size).skip((page-1)*size)

      ctx.body= {
        err:0,
        msg:'success',
        data:{total,list}
      }

    }
    // 增加管理员
    static async addUser(ctx){
      let { username,role } = ctx.request.body
      const roles = role.split(';').filter(e=>e)
      let role_name=''
      // if(roles.length>1) role_name='超级管理员'
      switch(role){
        case 'admin':
          role_name='管理员'
        break;
        case 'editor':
          role_name='编辑者'
        break;
        default:
          role_name='超级管理员'
      }
      const params={
        username,
        password:'123456',
        role,
        role_name,
        status:1
      }
      const user = await userModel.findOne({username})
      if (user) return ctx.body = { err: 1, msg: `${username}已被占用` }
      await userModel.insertMany([params])
      ctx.body = { err: 0, msg: '注册成功' }



    }

}
module.exports = UserController